<?php
	namespace Home\Controller;
	use Think\Controller;	
class OrderController extends Controller {
    function orders($key=0){
    	/*
		 * key表示要选择的订单状态，默认为0代表所有的订单,1-7代表订单的其他7种状态
		 * */	
    	$statussql="";	
    	if($key){
    		$statussql=" and status=".$key;
    	}
    	//分页相关
		$total=D('goods_order')->where("user_id=".session('id').$statussql)->count();
		$per=2;
		//实例化分页类对象
		$page_obj=new \Tools\CssPage($total,$per);
		$sql="select * from goods_order where user_id=".session('id').$statussql." order by create_time desc ".$page_obj->limit;
//  	$orders=D('goods_order')->where("user_id=".session('id'))->order("create_time desc")->select();
		$orders=D('goods_order')->query($sql);
		$pagelist=$page_obj->fpage(array(3,4,5,6,7,8));
		$this->assign('pagelist',$pagelist);
		$this->assign('total',$total);
		$this->assign("orders",$orders);
    	$this->display();
    }
	
	function makeorder(){//确认订单信息
			
//		var_dump($_POST['goods']);
//		$this->ajaxReturn($goods);
		$totalprice;
		foreach($_POST['goods'] as $k=>$v){//计算商品总价
			$totalprice+=(double)$v['price']*(int)$v['quantity'];
		}
//		echo $totalprice;
		$address=D('address')->where('user_id='.session('id'))->select();//获取用户保存的地址
//		var_dump($address);
		$score=D('user')->field('score')->where('id='.session('id'))->find();//获取用户积分
		//var_dump($score);
		$this->assign('score',$score['score']);
		$this->assign('address',$address);
		$this->assign("totalprice",$totalprice);	
		$this->assign("goods",$_POST['goods']);	
		$this->display();
		
	}
	function payorder($goods,$addressuid){//订单支付
//		$this->ajaxReturn($goods);
		$totalprice=0;
		$allgood=array();
		foreach($goods as $k=>$v){//计算商品总价
			$good=D('integralgoods')->where("id=".$v['id'])->find();
			$allgood[]=array("good"=>$good,"quantity"=>$v['quantity']);
			if($good['count']<$v['quantity']){//判断商品库存是否足够
				$this->ajaxReturn(array("errorcode"=>2,"error"=>"商品".$good['name']."库存不足"));
			}else{
				$totalprice+=(double)$good['price']*(int)$v['quantity'];
			}
//			var_dump($v[0]);exit;
		}
		$score=D('user')->field('score')->where('id='.session('id'))->find()['score'];//获取用户积分余额
//		echo $score;
		if($totalprice>$score){
			$this->ajaxReturn(array("errorcode"=>1,"error"=>"积分余额不足"));
		}else{//余额和库存足够,则进行购买
			$address=D('address')->where("uid=".$addressuid)->find();
			
			$o=array(
				"user_id"=>session('id'),
				"create_time"=>$_SERVER['REQUEST_TIME'],
				"paid_time"=>$_SERVER['REQUEST_TIME'],
				"paid_fee"=>$totalprice,
				"status"=>\Model\OrderModel::WAIT_SEND,//待发货状态
				"pay_type"=>2,
				"address"=>json_encode($address),
				"goods"=>json_encode($allgood),
			);
			$db=new \Model\DbModel();
//			$flag=true;//只有所有商品数量都正确减少时才为true,任何不成功都为false
			$db->startTrans();//开启事务
//			foreach($goods as $k=>$v){//逐个减少对应商品数量
//				if(!$db->updatedataforint("integralgoods",array("count"=>"count-".$v['quantity']),"id=".$v['id'])){
//					$flag=false;
//					break;
//				}
//			}
			foreach($goods as $k=>$v){//逐个减少对应商品数量
				$db->updatedataforint("integralgoods",array("count"=>"count-".$v['quantity']),"id=".$v['id']);
			}
			$score_res=$db->updatedataforint("user",array("score"=>"score-".$totalprice),"id=".session('id'));
			$order_res=D('goods_order')->add($o);
			if($order_res&&$score_res){
				\Tools\PublicController::send(\Tools\PublicController::gettoken());//发送微信公众号消息提醒商家
				$db->commit();//成功，提交事务
				$this->ajaxReturn(array("errorcode"=>0,"error"=>"下单成功"));
			}else{
				$db->rollback();//失败，事务回滚
				$this->ajaxReturn(array("errorcode"=>3,"error"=>"下单失败，未知错误!"));
			}
//			$this->ajaxReturn($flag);
		}
//		$this->ajaxReturn($goods);
	}
//用户确认收货
	function receivegoods($uid){
		$db=new \Model\DbModel();
		$res=$db->updatedata("goods_order",array("status"=>"3","recv_time"=>$_SERVER['REQUEST_TIME']),"uid=".$uid);
		if($res){
			$this->ajaxReturn(array("errorcode"=>0,"error"=>"确认收货成功"));
		}else{
			$this->ajaxReturn(array("errorcode"=>1,"error"=>"未知错误"));
		}
	}
	//用户发表评论
	function tocomment($uid,$goods_uid){
		if(!empty($_POST)){
			
			//上传评论图片
			$cfg=array('rootPath'      => './upload/');
			$up=new \Think\Upload($cfg);
			$upload_result=$up->uploadOne($_FILES['images']);
			//图片路径
			$pic_path=$up->rootPath.$upload_result['savepath'].$upload_result['savename'];
			//修改为新的图片路径
			$_POST['images']=ltrim($pic_path,'.');
			//添加新评论
			$_POST['order_uid']=$uid;
			$_POST['goods_uid']=$goods_uid;
			$_POST['parent_uid']=0;
			$_POST['user_uid']=session('id');
			$_POST['status']=1;
			$_POST['create_time']=$_SERVER['REQUEST_TIME'];
			//修改订单状态为已完成
			$db=new \Model\DbModel();
			$res1=$db->updatedataforint("goods_order",array("status"=>\Model\OrderModel::COMPLETE),"uid=".$uid);
			//添加评论
			$res2=D('goods_comment')->add($_POST);
			if($res1&&$res2){
				//商品评论数加1
				$db->updatedataforint("integralgoods",array("comment_cnt"=>"comment_cnt+1"),"id=".$goods_uid);
				echo "<script>alert('评论成功')</script>";
				$this->redirect('Order/orders',array(),1," ");
			}else{
				echo "<script>alert('评论失败')</script>";
				//$this->redirect('User/address',array(),1," ");
			}
//			var_dump($_POST);
//			echo $uid;
		}else{
			//判断用户是否登录并购买过此商品
			//需要先验证登录状态，没登录则跳转至登录界面
			$pc=new \Tools\PublicController();
			$my=$pc->require_login();
			$o=D('goods_order')->field("user_id")->where("uid=".$uid." and status=".\Model\OrderModel::WAIT_COMMENT)->find();
			if($o['user_id']!=$my['id']){
				echo "<script>alert('购买了商品并确认收货才可以评论哦！')</script>";
				$this->redirect('IntegralGoods/goalstore',array(),1," ");
			}
			//判断用户是否已经评论过此订单
			$sql="select * from goods_comment where order_uid=".$uid." and goods_uid=".$goods_uid." and user_uid=".$my['id'];
			if(D('goods_comment')->query($sql)){
				echo "<script>alert('你已经评论过此订单了哦！')</script>";
				$this->redirect('Order/orders',array(),1," ");
			}
//			var_dump($o);
			$this->display();
		}
	}
	//用户申请退款
	function torefund($uid){
		if(!empty($_POST)){
			$_POST['order_uid']=$uid;
			$_POST['user_uid']=session('id');
			$_POST['status']=0;
			$_POST['create_time']=$_SERVER['REQUEST_TIME'];
//			$o=D('goods_order')->field("paid_fee")->where("uid=".$uid)->find();
			//查找退款金额
			$_POST['refund_fee']=D('goods_order')->field("paid_fee")->where("uid=".$uid)->find()['paid_fee'];
			//设置订单状态为申请退款状态
			$db=new \Model\DbModel();
			$res1=$db->updatedataforint("goods_order",array("status"=>\Model\OrderModel::WAIT_REFUND),"uid=".$uid);
			//添加退款记录
			$res2=D('goods_refund')->add($_POST);
			if($res1&&$res2){
				echo "<script>alert('申请成功')</script>";
				$this->redirect('Order/orders',array(),1," ");
			}else{
				echo "<script>alert('申请失败')</script>";
				//$this->redirect('User/address',array(),1," ");
			}
//			var_dump($_POST);
		}else{
			$this->display();	
		}
	}
}